/*  Copyright 2011 Jason Jones
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.jasonwjones.hyperion.jessub;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * The Replacer class provides the ability to read from a file, look for any
 * codes that are to be replaced, and replaces them.
 * @author jasonwjones
 */
public class Replacer {

	/**
	 * Given a line of text, look for replacement tokens and replace them
	 * with their Jessub replacement vaule
	 * @param text the line of text to search
	 * @return the line of text with replacements (if any) performed
	 */
	public String extract(String text) {

		String resultingLine = text;
		
		String template = "\\$\\{([^}]+)\\}";
		Pattern p = Pattern.compile(template);
		Matcher m = p.matcher(text);

		while (m.find()) {
			String originalText = m.group();
			String replacementText = new Expression(m.group(1)).generate();
			resultingLine = resultingLine.replace(originalText, replacementText);
		}
		return resultingLine;
	}

	/**
	 * Runs through the input source line by line and performs transformations,
	 * if any. 
	 * @param input the BufferedReader to read from
	 * @param output the BufferedWriter to write to
	 * @throws IOException if a problem writing/reading the data
	 */
	public void process(BufferedReader input, BufferedWriter output) throws IOException {
		String strLine;
		while ((strLine = input.readLine()) != null) {
			String resultingLine = extract(strLine) + System.getProperty("line.separator");;
			output.write(resultingLine);
		}
		output.close();
	}
		
	/**
	 * Creates the specified output file based on running the conversion process
	 * on the input file
	 * @param inputFilename the name of the input file
	 * @param outputFilename the name of the output file
	 * @throws IOException
	 */
	public void process(String inputFilename, String outputFilename) throws IOException {
		BufferedReader in = new BufferedReader(new FileReader(inputFilename));
		BufferedWriter out = new BufferedWriter(new FileWriter(outputFilename));
		process(in, out);
	}
	
}
